package com.whwace.web;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.whwace.core.BusinessContext;
import com.whwace.core.FlowToolsUtil;
import com.whwace.exception.AppException;
import com.whwace.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@Slf4j
public class WebController {

  @GetMapping("/**")
  @SentinelResource(value = "executeGet", blockHandler = "handleBlock")
    public ResponseEntity<Map> executeGet(HttpServletRequest request, HttpServletResponse response) {
        BusinessContext ctx = null;
        try {
            ctx = new BusinessContext(request, response);
            FlowToolsUtil.doExecute(ctx,"common/handleCloudApi");
            return ResultUtil.ok(ctx.getParams());
        } catch (AppException e) {
            log.error("错误消息：",e.getMessage(),e);
            return ResultUtil.failure(ctx,e);
        } catch (Exception e){
            log.error("系统错误:",e);
            return ResultUtil.error(ctx,e);
        }
    }

    @PostMapping("/**")
    public ResponseEntity<Map> executePost(HttpServletRequest request, HttpServletResponse response) {
        BusinessContext ctx = null;
        try {
            ctx = new BusinessContext(request, response);
          FlowToolsUtil.doExecute(ctx, "common/handleCloudApi");
          return ResultUtil.ok(ctx);
        } catch (AppException e) {
          log.error("错误消息：", e.getMessage(), e);
          return ResultUtil.failure(ctx, e);
        } catch (Exception e) {
          log.error("系统错误:", e);
          return ResultUtil.error(ctx, e);
        }
    }

  public String handleBlock(BlockException ex) {
    return "接口被限流";
  }
}
